package com.badibadi.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;

import com.badibadi.adapter.AfterLandingMyHomePageAllAdapter_1;
import com.badibadi.adapter.Popwindows_Adapter;
import com.badibadi.fragment.ActivityOverViewFragment0;
import com.badibadi.fragment.BaseFragment;
import com.badibadi.fragment.CalendarFragment;
import com.badibadi.fragment.ActivityMyActivityFragment0.GetList;
import com.badibadi.fragment.CalendarFragment.CalendarGridViewAdapter;
import com.badibadi.infos.Activity_Overview_Model;
import com.badibadi.infos.Area_More_Activity_Model;
import com.badibadi.infos.ClueTypeModel;
import com.badibadi.infos.ListsModel;
import com.badibadi.infos.Results;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MySharePreferences;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.TempTools;
import com.badibadi.mytools.Utils;
import com.badibadi.uniclubber.R;
import com.badibadi.uniclubber.R.layout;
import com.badibadi.uniclubber.R.menu;
import com.view.my_view.XListView;
import com.view.my_view.XListView.IXListViewListener;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.drawable.BitmapDrawable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TextView;

/**
 * 地区的活动
 * 
 * @author Administrator initTabHostTHREE
 * 
 */
public class CalendarRigionActivity extends CalendarActivity {

	private int StartYY, StartMM, StartDD;
	private int EndYY, EndMM, EndDD;

	private TabHost tabhost;
	private Area_Rigion_Activity_Fragment0 activity_Fragment0;
	private Bundle bun;
	private String areaid;
	private List<Activity_Overview_Model> activity_Overview_Models;
	private TextView calendar_title;
	private Button calendar_return_btn;
	private boolean is_true = true;
	private ListsModel listsModel;
	private Handler mmHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				calendar_title.setText(msg.getData().getString("tital"));
				break;

			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		init();
		TextView tv = (TextView) this.findViewById(R.id.calendar_title);
		tv.setText("");
		LoadFragment(1, null);
		ChangeToThreeTab();
		Mode_switching.setVisibility(View.GONE);
	}

	@Override
	public void initCalendarFragment(final List<Activity_Overview_Model> models) {
		FragmentTransaction transaction = manager.beginTransaction();
		calendarFragment = CalendarFragment.getInstance();
		calendarFragment
				.setOnCalendarOnClistener(new CalendarFragment.CalendarListener() {

					@Override
					public boolean AddStartButton(int Year, int Month, int Day) {
						// TODO Auto-generated method stub
						return ShowStartButton(Year, Month, Day, StartYY,
								StartMM, StartDD);
					}

					@Override
					public boolean AddEndButton(int Year, int Month, int Day) {
						// TODO Auto-generated method stub
						return ShowEndButton(Year, Month, Day, EndYY, EndMM,
								EndDD);
					}

					@Override
					public String AddActivity(int Year, int Month, int Day) {
						// TODO Auto-generated method stub

						// if (Year == 2014 && Month == 8 && Day == 8) {
						// return "是福建省懂了否";
						// }
						// if (Year == 2014 && Month == 8 && Day == 9) {
						// return "是福建省懂了";
						// }

						return ShowActivity(Year, Month, Day,
								activity_Fragment0
										.getActivity_Overview_Models());
					}
				});
		calendarFragment
				.setOnCalendarItemClistener(new CalendarFragment.CalendarGridViewListener() {

					@Override
					public void ItemListener(AdapterView<?> arg0, View view,
							int position, long arg3,
							CalendarGridViewAdapter calendaradapter) {
						// TODO Auto-generated method stub
						initOnCalendarItemClistener(arg0, view, position, arg3,
								calendaradapter);
					}
				});
		transaction.replace(R.id.calendar_layout, calendarFragment);
		transaction.commit();
	}

	private void init() {
		try {
			areaid = getIntent().getStringExtra("areaid");
		} catch (Exception e) {
			e.printStackTrace();
		}
		// bottom_btn1 = (RelativeLayout)
		// findViewById(R.id.calender_bottom_btn1);
		// bottom_btn2 = (RelativeLayout)
		// findViewById(R.id.calender_bottom_btn2);
		bottom_btn1.setSelected(false);
		bottom_btn2.setSelected(true);
		calendar_title = (TextView) this.findViewById(R.id.calendar_title);
		calendar_return_btn = (Button) findViewById(R.id.calendar_return_btn);
		calendar_return_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if (activity_Fragment0 != null && is_true) {
					activity_Fragment0.AreaActivitySet();
				} else {
					finish();
				}
			}
		});

		// title.setText("美国的活动");
	}

	@Override
	public void OnClick0(View view) {
		// TODO Auto-generated method stub
		super.OnClick0(view);
		is_true = false;
	}

	@Override
	protected void initTabHostTWO(int id, int id2) {
		// TODO Auto-generated method stub
		super.initTabHostTWO(id, id2);
	}

	@Override
	public void initTabHostTHREE(int id, int id2, int id3) {
		// TODO Auto-generated method stub
		super.initTabHostTHREE(id, id2, R.string.Nearby);
	}

	@Override
	public void initListFragment(int t, String yes) {
		// TODO Auto-generated method stub
		FragmentTransaction transaction = manager.beginTransaction();
		activity_Fragment0 = new Area_Rigion_Activity_Fragment0();
		// transaction = manager.beginTransaction();
		bun = new Bundle();
		bun.putInt("type", t);
		activity_Fragment0.setArguments(bun);
		transaction.replace(R.id.calendar_layout, activity_Fragment0);
		transaction.commit();
	}

	// /**
	// * 需要重写的，下面的日历模式的按钮
	// */
	// @Override
	// public void OnChageTabHost0() {
	// // TODO Auto-generated method stub
	// GoneAllTabHost();
	// }

	/**
	 * 需要重写的，下面的列表模式的按钮
	 */
	@Override
	public void OnClick1(View view) {
		// TODO Auto-generated method stub
		super.OnClick1(view);
		is_true = true;
	}

	@SuppressLint("ValidFragment")
	public class Area_Rigion_Activity_Fragment0 extends BaseFragment implements
			IXListViewListener {
		private AfterLandingMyHomePageAllAdapter_1 x1Adapter;
		private XListView xListView1;
		private PopupWindow popup = null;
		private int Page;// 当前显示数据页数
		private int Type;// 显示类型
		private List<Activity_Overview_Model> activity_Overview_Models;
		private int languageType = 0;
		private MySharePreferences preferences;
		private List<ClueTypeModel> clueTypeModels;
		private Popwindows_Adapter popwindows_Adapter;
		private ListView type_list;
		private Results results;
		private boolean judge;
		private Message message;
		private Bundle bundle;
		// private List<Activity_Overview_Model> list;
		private Area_More_Activity_Model activity_Model;
		private TextView tv_search;
		private LinearLayout ll_search;
		private boolean isReturnUp = true;// 按返回键是否回退关键字
		private boolean isSouSuo1 = true;
		private boolean isSouSuo2 = true;
		private LinearLayout Keyword_Frame;
		// 查询关键字相关
		private String searchName = null;
		private String tid = "0";// 活动类型id

		private Handler mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 1:
					try {
						Utils.ExitPrgress(CalendarRigionActivity.this);
						Utils.showMessage(CalendarRigionActivity.this,
								getResources().getString(R.string.l_net_error));
						xListView1.stopRefresh();
						xListView1.stopLoadMore();
						xListView1.setRefreshTime(""
								+ getResources().getString(R.string.ganggang));
					} catch (Exception e) {
						// TODO: handle exception
					}

					break;
				case 2:
					try {
						Utils.ExitPrgress(CalendarRigionActivity.this);
						activity_Overview_Models.addAll(activity_Model
								.getActivitys());
						x1Adapter.notifyDataSetChanged();
						if (judge) {
							message = new Message();
							bundle = new Bundle();
							message.what = 1;
							bundle.putString(
									"tital",
									activity_Model.getArea().getArea_name()
											+ getResources().getString(
													R.string.l_xb38));
							message.setData(bundle);
							mmHandler.sendMessage(message);
							judge = false;
						}
						xListView1.stopRefresh();
						xListView1.stopLoadMore();
						xListView1.setRefreshTime(""
								+ getResources().getString(R.string.ganggang));
					} catch (Exception e) {
						// TODO: handle exception
					}

					break;
				case 3:
					try {
						Utils.ExitPrgress(CalendarRigionActivity.this);
						Utils.showMessage(CalendarRigionActivity.this,
								getResources().getString(R.string.l_xa10));
						xListView1.stopRefresh();
						xListView1.stopLoadMore();
						xListView1.setRefreshTime(""
								+ getResources().getString(R.string.ganggang));
					} catch (Exception e) {
						// TODO: handle exception
					}

					break;
				case 4:
					try {
						Utils.ExitPrgress(CalendarRigionActivity.this);
						// clueTypeModels.add(0, model);
						if (clueTypeModels != null) {
							clueTypeModels.clear();
						}
						if (listsModel.getLists() != null
								&& !listsModel.getLists().isEmpty()) {
							for (int i = 0; i < listsModel.getLists().size(); i++) {
								ClueTypeModel clueTypeModel = new ClueTypeModel();
								clueTypeModel.setId(listsModel.getLists()
										.get(i).getId());
								clueTypeModel.setName(listsModel.getLists()
										.get(i).getName());
//								clueTypeModel.setNum(listsModel.getLists()
//										.get(i).getNum());
								clueTypeModels.add(clueTypeModel);
							}
						}
						popwindows_Adapter = new Popwindows_Adapter(
								clueTypeModels, CalendarRigionActivity.this);
						type_list.setAdapter(popwindows_Adapter);
						type_list
								.setOnItemClickListener(new OnItemClickListener() {
									@Override
									public void onItemClick(
											AdapterView<?> arg0, View arg1,
											int position, long arg3) {
										tid = clueTypeModels.get(position)
												.getId();
										tv_search.setVisibility(View.VISIBLE);
										ll_search.setVisibility(View.GONE);
										tv_search.setText(clueTypeModels.get(
												position).getName());
										isSouSuo1 = false;
										Page = 1;
										activity_Overview_Models.clear();
										x1Adapter.notifyDataSetChanged();
										activitise(
												Type,
												Page,
												areaid,
												com.badibadi.mytools.Dialog
														.getSystemLanguageType(CalendarRigionActivity.this));
										if (popup != null) {
											popup.dismiss();
										}
									}
								});
					} catch (Exception e) {
						// TODO: handle exception
					}

					break;
				default:
					break;
				}
			}
		};
		private LinearLayout acticity_overview0_btn_type;

		@Override
		public void onCreate(Bundle savedInstanceState) {
			// TODO Auto-generated method stub
			super.onCreate(savedInstanceState);
		}

		@Override
		public View onCreateView(final LayoutInflater inflater,
				ViewGroup container, Bundle savedInstanceState) {
			// TODO Auto-generated method stub
			View view = inflater.inflate(
					R.layout.activity_overview_importylayout, null);
			Page = 1;
			judge = true;
			tv_search = (TextView) view.findViewById(R.id.TheKeyword);
			ll_search = (LinearLayout) view.findViewById(R.id.seach_ll);
			Keyword_Frame = (LinearLayout) view
					.findViewById(R.id.Keyword_Frame);
			Keyword_Frame.setVisibility(View.GONE);
			Type = getArguments().getInt("type", 1);
			clueTypeModels = new ArrayList<ClueTypeModel>();
			activity_Overview_Models = new ArrayList<Activity_Overview_Model>();
			x1Adapter = new AfterLandingMyHomePageAllAdapter_1(
					activity_Overview_Models, CalendarRigionActivity.this,
					Type, 0.0, 0.0, "2");
			preferences = new MySharePreferences(getActivity(), "language");
			languageType = preferences.get("language", 0);
			InitMyXListView1(view);
			activitise(Type, Page, areaid,
					com.badibadi.mytools.Dialog
							.getSystemLanguageType(CalendarRigionActivity.this));
			acticity_overview0_btn_type = (LinearLayout) view
					.findViewById(R.id.fragment_club_overview0_btn_type);
			acticity_overview0_btn_type
					.setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							OpenOrClosePopWindows(inflater, v);
						}
					});

			return view;
		}

		public void AreaActivitySet() {
			if (ll_search.getVisibility() == 8) {// 隐藏
				// System.out.println("隐藏状态，变为显示");
				// searchName = null;
				ll_search.setVisibility(View.VISIBLE);
				tv_search.setVisibility(View.GONE);
				Page = 1;
				tid = "0";
				activity_Overview_Models.clear();
				x1Adapter.notifyDataSetChanged();
				activitise(
						Type,
						Page,
						areaid,
						com.badibadi.mytools.Dialog
								.getSystemLanguageType(CalendarRigionActivity.this));
			} else {
				((getActivity())).finish();
				getActivity().overridePendingTransition(R.anim.slide_left2,
						R.anim.slide_right2);
			}
		}

		private void activitise(final int type, final int page,
				final String areaid, final String languageType) {
			MyThreadTool.fixedThreadPool.execute(new Runnable() {
				@Override
				public void run() {
					String actcontent = Utils.getRequest(Constants.BadiUrl_1
							+ "area/activitise?areaId=" + areaid
							+ "&languageType=" + languageType + "&type=" + type
							+ "&page=" + page + "&showNum=8&activityType="
							+ tid);
					// Log.v("sss1", "获取地区活动提交的数据是:" + Constants.BadiUrl_1
					// + "area/activitise?areaId=" + areaid
					// + "&languageType=" + languageType + "&type=" + type
					// + "&page=" + page + "&showNum=8&activityType="
					// + tid);
					if (actcontent != null) {
						// System.out.println("地区活动返回结果是:" + actcontent);
//						Log.v("sss1", "地区活动返回结果是:" + actcontent);
						results = Utils.checkResult_NNN(
								getApplicationContext(), actcontent);
						// Log.v("sss1",
						// "数据是:" + results + " " + results.getRetmsg()
						// + " " + results.isRet());
						if (results != null
								&& !results.getRetmsg().equals("null")
								&& results.isRet()) {
							try {
								activity_Model = new Area_More_Activity_Model();
								activity_Model = JSONUtils
										.getEntityByJsonString(
												results.getRetmsg(),
												Area_More_Activity_Model.class);
								mHandler.sendEmptyMessage(2);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						} else {
							if (page > 1) {
								--Page;
							} else {
								Page = 1;
							}
							mHandler.sendEmptyMessage(3);
						}
					} else {
						if (page > 1) {
							--Page;
						} else {
							Page = 1;
						}
						mHandler.sendEmptyMessage(1);
					}
				}
			});
		}

		private void Show_type_activity_1() {
			Utils.showPrgress(CalendarRigionActivity.this);
			MyThreadTool.fixedThreadPool.execute(new Runnable() {
				@Override
				public void run() {
					listsModel = new ListsModel();
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("type", "huodong");
					map.put("languageType",
							TempTools.BackLanguage(languageType));
					String acticontent = Utils.sendRequest(map,
							Constants.BadiUrl_1 + "type/listType");
					if (acticontent != null) {
						Results results = Utils.checkResult_NNN(
								getApplicationContext(), acticontent);
						if (results != null && results.getRetmsg() != null) {
							// System.out.println("结果是:" + results.getRetmsg());
							try {
								listsModel = JSONUtils.getEntityByJsonString(
										results.getRetmsg(), ListsModel.class);
								System.out.println("diquhuodong"+results.getRetmsg());
								mHandler.sendEmptyMessage(4);
							} catch (Exception e) {
								e.printStackTrace();
							}
						} else {
							mHandler.sendEmptyMessage(3);
						}
					} else {
						mHandler.sendEmptyMessage(1);
					}
				}
			});
		}

		/**
		 * 打开或管理悬浮对话框
		 * 
		 * @param inflater
		 * @param v
		 */
		public void OpenOrClosePopWindows(LayoutInflater inflater, View v) {

			View root = inflater.inflate(
					R.layout.fragment_club_overview_popwindows, null);
			popup = new PopupWindow(root,
					LinearLayout.LayoutParams.MATCH_PARENT,
					LinearLayout.LayoutParams.MATCH_PARENT);
			type_list = (ListView) root.findViewById(R.id.type_list);
			popup.setBackgroundDrawable(new BitmapDrawable());
			popup.setFocusable(true);
			popup.setTouchable(true);
			Show_type_activity_1();
			popup.showAsDropDown(v);

		}

		public void InitMyXListView1(View view) {
			xListView1 = (XListView) view
					.findViewById(R.id.after_landing_friends00_xlistView2);
			// xListView1.setDividerHeight(10);
			xListView1.setPadding(10, 10, 10, 10);
			xListView1.setXListViewListener(this);
			xListView1.setPullLoadEnable(true);
			xListView1.setPullRefreshEnable(true);
			xListView1.setAdapter(x1Adapter);
		}

		@Override
		public void onRefresh() {
			// TODO Auto-generated method stub
			Page = 1;
			if (activity_Overview_Models != null) {
				activity_Overview_Models.clear();
			}
			activitise(Type, Page, areaid,
					com.badibadi.mytools.Dialog
							.getSystemLanguageType(CalendarRigionActivity.this));
		}

		@Override
		public void onLoadMore() {
			// TODO Auto-generated method stub
			activitise(Type, ++Page, areaid,
					com.badibadi.mytools.Dialog
							.getSystemLanguageType(CalendarRigionActivity.this));
		}

		public List<Activity_Overview_Model> getActivity_Overview_Models() {
			return activity_Overview_Models;
		}

		public void setActivity_Overview_Models(
				List<Activity_Overview_Model> activity_Overview_Models) {
			this.activity_Overview_Models = activity_Overview_Models;
		}
	}
}
